package com.gitee.cirnochat.common.config;

import com.gitee.cirnochat.chat.consumer.MessageConsumer;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.gitee.cirnochat.common.constant.MQConstant.CHAT_QUEUE_NAME;
import static com.gitee.cirnochat.common.constant.MQConstant.MESSAGE_EXCHANGE;
import static com.gitee.cirnochat.common.constant.MQKey.CHAT_MESSAGE_ROUTE_ROUTING_KEY;

@Configuration
@RequiredArgsConstructor
public class RabbitListenerConfig {

    private final ConnectionFactory connectionFactory;

    private final WebSocketConfig webSocketConfig;

    private final MessageConsumer consumer;

    @Bean
    public List<SimpleMessageListenerContainer> listenerContainers() {
        List<SimpleMessageListenerContainer> containers = new ArrayList<>();

        Map<String, String> handlerRoutingKeys = Map.of(
                "handleMessage", CHAT_MESSAGE_ROUTE_ROUTING_KEY + '-' + webSocketConfig.getNodeId()
        );

        for (Map.Entry<String, String> entry : handlerRoutingKeys.entrySet()) {
            String methodName = entry.getKey();
            String routingKey = entry.getValue();
            String queueName = methodName + CHAT_QUEUE_NAME;  // 你可以定义成更合适的名字

            // 声明交换机、队列、绑定
            DirectExchange exchange = new DirectExchange(MESSAGE_EXCHANGE);
            Queue queue = new Queue(queueName, true);
            Binding binding = BindingBuilder.bind(queue).to(exchange).with(routingKey);

            RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
            rabbitAdmin.declareExchange(exchange);
            rabbitAdmin.declareQueue(queue);
            rabbitAdmin.declareBinding(binding);

            // 创建监听器容器
            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            container.setQueueNames(queueName);
            container.setMessageListener(new MessageListenerAdapter(consumer, methodName));

            containers.add(container);
        }

        return containers;
    }
}
